package org.mosquitos.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import net.jxta.endpoint.Message;
import net.jxta.endpoint.StringMessageElement;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeService;
import net.jxta.pipe.OutputPipe;
import net.jxta.protocol.PipeAdvertisement;

public class PipeSendService implements Runnable {
	private PeerGroup peerGroup;
	private Map<String,Object> userList;
	public final static String MESSAGE_NAME_SPACE = "PipeTest";
	private String name;
	
	public PipeSendService(PeerGroup peerGroup,Map<String,Object> userList,String name){
		this.peerGroup = peerGroup;
		this.userList = userList;
		this.name = name;
	}
	
	public void run(){
		while(true){
			System.out.println("what ?:");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String content=null;
			try {
				content = br.readLine();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			PipeService pipeService = peerGroup.getPipeService();
			OutputPipe outputPipe = null;
			try {
				outputPipe = pipeService.createOutputPipe(AdvertisementCreator.createAdv(peerGroup, name, PipeService.UnicastType, "urn:jxta:uuid-59616261646162614E504720503250333CF917BFDA5E464FA4DFBF84736ED2F904"), 10000L);
				System.out.println("here");
			} catch (IOException e) {
				e.printStackTrace();
			}
			Message message = new Message();
			message.addMessageElement(new StringMessageElement(MESSAGE_NAME_SPACE, content, null));
			try {
				outputPipe.send(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			outputPipe.close();
			System.out.println("send to:"+outputPipe.getPipeID().toString());
		}
	}
	
	/*
	public void run(){
		String serviceName= pg.getPeerID().getUniqueValue().toString();
		
        while(true){
        	System.out.println("to who ?:");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            
            String key=null;
			try {
				key = br.readLine();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
            if(userList.containsKey(key)){
				System.out.println("what ?:");
				BufferedReader br_ = new BufferedReader(new InputStreamReader(System.in));
				String content=null;
				try {
					content = br_.readLine();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				PeerAdvertisement pa = (PeerAdvertisement)userList.get(key);
				
				PipeService ps = pg.getPipeService();
				//OutputPipe op = ps.createOutputPipe((PeerAdvertisement)userList.get(key), 1000000L);
            }
        }
	}
	*/
}
